package com.micai.springboot.listener;

import com.micai.springboot.event.OnSendEmailEvent;
import com.micai.springboot.event.OnSendSmsEvent;
import com.micai.springboot.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/7/23 14:42
 * @Description: 自定义发送邮件事件监听器，并直接把该监听器注册成组件
 */
@Component
public class AsyncEventListener implements ApplicationListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(AsyncEventListener.class);

    @Autowired
    private MailService mailService;

    @Async
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (applicationEvent instanceof OnSendEmailEvent) {
            String to = ((OnSendEmailEvent) applicationEvent).getTo();
            String subject = ((OnSendEmailEvent) applicationEvent).getSubject();
            String content = ((OnSendEmailEvent) applicationEvent).getContent();
            this.confirmSendEmail(to, subject, content);
        } else if (applicationEvent instanceof OnSendSmsEvent) {
            String to = ((OnSendSmsEvent) applicationEvent).getTo();
            String content = ((OnSendSmsEvent) applicationEvent).getContent();
            this.confirmSendSms(to, content);
        }
    }

    private void confirmSendEmail(final String to, final String subject, final String content) {
        long start = System.currentTimeMillis();
        // TODO 调用发送邮件接口
        mailService.sendHtmlMail(to, subject, content);
        long end = System.currentTimeMillis();
        LOGGER.info("发送邮件验证码耗时：" + (end - start) + " 毫秒!");
    }

    private void confirmSendSms(final String to, final String content) {
        long start = System.currentTimeMillis();
        // TODO 调用发送短信接口
        long end = System.currentTimeMillis();
        LOGGER.info("发送短信验证码耗时：" + (end - start) + " 毫秒!");
    }
}
